<template>
  <div :style="mapStyle" :id="uuid"></div>
</template>
<script>
/* eslint-disable no-undef */
export default {
  props: {
    value: Object,
    mapHeight: {
      type: Number,
      default: 100
    },
    level: {
      type: Number,
      default: 16
    },
    mode: {
      type: String,
      default: "location"
    }
  },
  created() {
    this.point = new BMap.Point(this.value.lng, this.value.lat);
  },
  mounted: function() {
    this.uuid = `vux-bmap-${Math.random()
      .toString(36)
      .substring(3, 8)}`;

    this.$nextTick(function() {
      // this.$el.setAttribute('id', `vux-bmap-${this.uuid}`)
      // this.map = new BMap.Map(`vux-bmap-${this.uuid}`)
      this.map = new BMap.Map(this.uuid);
      this.geolocation = new BMap.Geolocation();

      this.posMarker = new BMap.Marker(this.point, {
        icon: new BMap.Symbol(BMap_Symbol_SHAPE_POINT, {
          scale: 1.5,
          fillColor: "red",
          fillOpacity: 0.8
        })
      });

      this.posMarker.enableDragging();

      this.posMarker.addEventListener("dragend", e => {
        this.point = e.point;
      });

      this.map.addOverlay(this.posMarker);

      switch (this.mode) {
        case "location":
          this.initForLocationMode();
          break;
      }

      this.$watch("point", val => {
        this.$emit("input", val);
      });
    });
  },
  data() {
    return {
      uuid: "",
      point: {},
      mapStyle: {
        width: "100%",
        height: this.mapHeight + "px",
        borderRadius: "5px"
      }
    };
  },
  methods: {
    // 展示模式
    initForLocationMode() {
      var _this = this;

      if (this.point.lng === 0 && this.point.lat === 0) {
        this.geolocation.getCurrentPosition(
          function(r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
              _this.point = r.point;
              _this.posMarker.setPosition(r.point);
              _this.map.centerAndZoom(r.point, _this.level);
            }
          },
          { enableHighAccuracy: true }
        );
      } else {
        this.posMarker.setPosition(this.point);
        this.map.centerAndZoom(this.point, this.level);
      }

      // this.map.disableDragging()
      // this.map.disableScrollWheelZoom()
      this.map.disableDoubleClickZoom();
      this.map.addEventListener("click", function(e) {
        _this.posMarker.setPosition(e.point);
        _this.point = e.point;
      });
    }
  }
};
</script>
<style scoped>
</style>
